const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const lessMiddleware = require('less-middleware');
const logger = require('morgan');

const fileUpload = require('express-fileupload');
const cors = require('cors');
const morgan = require('morgan');
const _ = require('lodash');

const {jsonResponse} = require('./libs/jsonResponse');

const jwtAuth = require('./libs/jws');
// const jwt = require('express-jwt');
// const { secretKey } = require('./libs/constant');

const db = require('./libs/db')("./dbf/");


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users')(_,fileUpload,db,jwtAuth);
var apiRouter = require('./routes/api')(_,fileUpload,db,jwtAuth);

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// enable files upload
app.use(fileUpload({
  createParentPath: true
}));
app.use(cors());

app.use(jwtAuth);

app.use(morgan('dev'));

app.use(logger('dev'));
app.use(express.json({limit: '30mb'}));
app.use(express.urlencoded({ limit: '30mb',  extended: false }));
app.use(cookieParser());
app.use(lessMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('*',function(req, res, next) {
  res.header('Access-Control-Expose-Headers','token, authorization, date, Access-Control-Allow-Origin, Connection, ETag, X-Powered-By');
  next();
})
// app.use('*',function(req, res, next) {
//   // console.log(JSON.stringify(req.headers));
//   if(req.headers.origin){
//     res.header("Access-Control-Allow-Origin", req.headers.origin); // update to match the domain you will make the request from
//   }
//   if(req.headers.Origin){
//     res.header("Access-Control-Allow-Origin", req.headers.Origin); // update to match the domain you will make the request from
//   }
//   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, token, Referer, Referrer-Policy, Accept, WithCredentials");
//   res.header("Content-Type", "application/json;charset=utf-8");
//   // next();
//   if(req.method=='OPTIONS'){
//     res.status(200).send('ok');
//     // next();
//   }else{
//     next();
//   }
// });
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', apiRouter);
app.use('*',jsonResponse());

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
